chatRemote = require '../remote/chatRemote'
module.exports = (app) ->
	 new Handler app

class Handler
	constructor: (app)->
		@app = app

	send:(msg, session, next)=>
		rid = session.get 'rid'
		username = session.uid.split('*')[0]
		channelService = this.app.get 'channelService'
		param = {
			route: 'onChat',
			msg: msg.content,
			from: username,
			target: msg.target
		}
		channel = channelService.getChannel rid, false

		# the target is all users
		if msg.target == '*'
			channel.pushMessage param
		# the target is specific user
		else
			tuid = "#{msg.target}*#{rid}"
			tsid = channel.getMember(tuid)['sid']
			channelService.pushMessageByUids param, [{
				uid: tuid,
				sid: tsid
			}]
		next null, {route: msg.route}